//
//  MCEditSpecificationsViewController.swift
//  StoreManage
//
//  Created by MC on 2018/2/7.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

class MCEditSpecificationsViewController: MCViewController {

    var model : MCSpecificationsModel?
    var goodsId = 0
    var isAddSepc = false    // 是否新增规格  是的话，显示删除按钮

    private var isUpdateImage = false // 是否上传了规格图
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking()
    }
    
    // MARK: - System Delegate
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    // MARK: - Custom Delegate
    
    // MARK: - Action
    @objc func keyboardConfirmClicked() {
        self.view.endEditing(true)
    }

    
    @objc func rightItemClicked() {
        // 删除库存
        let para = [
            "goodsId" : model?.goodsId ?? 0,
            "productId" : model?.productId ?? 0,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_deleteSpecDesc, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            
            MCHUD_text(message: "成功删除规格", view: self.view, delay: 1.2)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                self.navigationController?.popViewController(animated: true)
            })
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    
    @objc func addImageViewClieked() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
            let vc = UIImagePickerController()
            vc.delegate = self
            vc.allowsEditing = true
            vc.sourceType = UIImagePickerControllerSourceType.photoLibrary
            self.present(vc, animated: true, completion: { })
        }
    }


    @objc func startUsingButtonClecked() {
        startUsingButton.isSelected = !startUsingButton.isSelected
    }

    
    
    @objc func saveButtonClecked() {
        
        
        
        
        
        // 判断是否填写
        if specView.textField.text?.count == 0 {
            MCHUD_text(message: "请填写规格", view: self.view, delay: 1.2)
            return
        }
        
        if orderView.textField.text?.count == 0 {
            MCHUD_text(message: "请填写货号", view: self.view, delay: 1.2)
            return
        }

        if moneyView.textField.text?.count == 0 {
            MCHUD_text(message: "请填写售价", view: self.view, delay: 1.2)
            return
        }

        if numberView.textField.text?.count == 0 {
            MCHUD_text(message: "请填写库存", view: self.view, delay: 1.2)
            return
        }
        
        if isUpdateImage == false {
            MCHUD_text(message: "请选择规格图", view: self.view, delay: 1.2)
            return
        }

        
        
        
        let imageData = UIImageJPEGRepresentation(addImageView.image!, 0.1)
        let base = imageData?.base64EncodedString() ?? ""
        
        let para = [
            "catalog" : "3",
            "suffix"  : "png",
            "imgBase" : base
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_imageBasePath, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            let imgUrl = response["data"] as? String ?? ""
            
            self.createSpec(imagePath: imgUrl)
        }, dislike: { (response) in }) { (error) in  }
    }
    
    
    func createSpec(imagePath:String) {
        var status : Int?
        
        if startUsingButton.isSelected {
            status = 1
        } else {
            status = 0
        }
        

   
        let money = Double(moneyView.textField.text!)!*100
        let moneyInt = Int(money)
        let moneyStr = String(moneyInt)

        
        let para = [
            "goodsId" : goodsId,
            "imagePath" : imagePath,
            "inventoryNum" : numberView.textField.text ?? "",
            "productBn" : orderView.textField.text ?? "",
            "salePrice" : moneyStr,
            "specification" : specView.textField.text ?? "",
            "status" : status!,
            "productId" : model?.productId ?? 0,
            "specDetailId" : model?.specDetailId ?? 0
            ] as [String : Any]
        
        var urlStr : String?
        if isAddSepc {
            urlStr = JAVA_addGoodsSpecDesc
        } else {
            urlStr = JAVA_updateSpecDesc
        }

        
        MCNetwork_post(url: urlStr!, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            
            var str : String?
            if self.isAddSepc {
                str = "新增规格成功"
            } else {
                str = "修改规格成功"
            }
            
            
            MCHUD_text(message: str!, view: self.view, delay: 1.2)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                self.navigationController?.popViewController(animated: true)
            })
            
        }, dislike: { (response) in }) { (error) in }

    }
    
    
    
    
    // MARK: - Network
    func sendNetworking() {
        
        if model == nil {
            return
        }
        
        self.isUpdateImage = true
        specView.textField.text = model?.specification
        orderView.textField.text = model?.productBn
        
        if model?.salePrice != 0 {
            let money = String.init(format: "%.2f", ((Double((model?.salePrice)!))/100.0))

            moneyView.textField.text = money
        }
        if model?.inventoryNum != 0 {
            let number : String = String.init(format: "%ld", (model?.inventoryNum)!)
            numberView.textField.text = number
        }
        

        addImageView.sd_setImage(with: URL.init(string: (model?.imagePath)!), placeholderImage: #imageLiteral(resourceName: "Reuse_placeholder_1_1"))
        
        if model?.status == 1 {
            startUsingButton.isSelected = true
        } else {
            startUsingButton.isSelected = false
        }
    }
    
    // MARK: - Method
    func baseSetting() {
        self.title = "规格详情"
        self.view.backgroundColor = UIColor.white
        
        if !isAddSepc {
            
            navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("删除", target: self, selector: #selector(rightItemClicked))
        }
    }
    
    func initUI() {
        view.addSubview(specView)
        specView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(view)
            make.top.equalTo(view)
            make.height.equalTo(44)
        }
        
        view.addSubview(orderView)
        orderView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(view)
            make.top.equalTo(specView.snp.bottom)
            make.height.equalTo(44)
        }

        view.addSubview(moneyView)
        moneyView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(view)
            make.top.equalTo(orderView.snp.bottom)
            make.height.equalTo(44)
        }

        view.addSubview(numberView)
        numberView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(view)
            make.top.equalTo(moneyView.snp.bottom)
            make.height.equalTo(44)
        }

        view.addSubview(addImageLabel)
        addImageLabel.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(view).offset(10)
            make.top.equalTo(numberView.snp.bottom)
            make.height.equalTo(44)
        }
        
        view.addSubview(addImageView)
        addImageView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.top.equalTo(addImageLabel.snp.bottom)
            make.size.equalTo(CGSize.init(width: 100, height: 100))
        }
        
        view.addSubview(startUsingButton)
        startUsingButton.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.top.equalTo(addImageView.snp.bottom).offset(10)
            make.size.equalTo(CGSize.init(width: 100, height: 40))
        }
     
        view.addSubview(saveButton)
        saveButton.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(44)
        }
    }
    
    
    func MCAddToolBar(textField:UITextField) {
        let bar = UIToolbar.init(frame: CGRect.init(x: 0, y: 0, width: MCScreenWidth, height: 44))
        let button = UIButton.init(frame: CGRect.init(x: MCScreenWidth-80, y: 7, width: 70, height: 30))
        button.layer.cornerRadius = 5
        button.layer.masksToBounds = true
        button.layer.borderColor = UIColor.MCMain.cgColor
        button.layer.borderWidth = 1
        button.setTitle("确认", for: UIControlState.normal)
        button.setTitleColor(UIColor.MCMain, for: UIControlState.normal)
        button.titleLabel?.font = MCFont(14)
        button.addTarget(self, action: #selector(keyboardConfirmClicked), for: UIControlEvents.touchUpInside)
        bar.addSubview(button)
        bar.layoutIfNeeded()
        bar.sendSubview(toBack: bar.subviews.last!)
        textField.inputAccessoryView = bar
    }

    
    // MARK: - Setter & Getter
    lazy var specView: MCAddTicketInputView = {
        let view = MCAddTicketInputView()
        view.titleLabel.text = "规格:"
        view.textField.placeholder = "请输入规格，例如蓝色 m"
        view.textField.delegate = self
        view.textField.returnKeyType = UIReturnKeyType.done
        return view
    }()
    
    lazy var orderView: MCAddTicketInputView = {
        let view = MCAddTicketInputView()
        view.titleLabel.text = "货号:"
        view.textField.placeholder = "请输入货号"
        view.textField.delegate = self
        view.textField.returnKeyType = UIReturnKeyType.done
        return view
    }()
    
    lazy var moneyView: MCAddTicketInputView = {
        let view = MCAddTicketInputView()
        view.titleLabel.text = "售价(元):"
        view.textField.placeholder = "请输入售价"
        view.textField.keyboardType = UIKeyboardType.decimalPad
        view.textField.delegate = self
        MCAddToolBar(textField: view.textField)
        return view
    }()
    
    lazy var numberView: MCAddTicketInputView = {
        let view = MCAddTicketInputView()
        view.titleLabel.text = "库存(件):"
        view.textField.placeholder = "请输入库存"
        view.textField.keyboardType = UIKeyboardType.numberPad
        view.textField.delegate = self
        return view
    }()
    
    lazy var addImageLabel: UILabel = {
        let label = UILabel()
        label.font = MCFont(14)
        label.text = "规格图"
        label.textColor = UIColor.black
        return label
    }()
    
    lazy var addImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.isUserInteractionEnabled = true
        imageView.image = #imageLiteral(resourceName: "GoodsManage_add_square")
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(addImageViewClieked))
        imageView.addGestureRecognizer(tap)
        return imageView
    }()
    
    lazy var startUsingButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.titleLabel?.font = MCFont(13)
        button.setTitle("  启用", for: UIControlState.normal)
        button.setTitleColor(UIColor.black, for: UIControlState.normal)
        button.setImage(#imageLiteral(resourceName: "GoodsManage_notSelected"), for: UIControlState.normal)
        button.setImage(#imageLiteral(resourceName: "GoodsManage_selected"), for: UIControlState.selected)
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
        button.isSelected = true
        button.addTarget(self, action: #selector(startUsingButtonClecked), for: UIControlEvents.touchUpInside)

        return button
    }()
    
    lazy var saveButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.backgroundColor = UIColor.MCMain
        button.titleLabel?.font = MCFont(16)
        button.setTitle("保存", for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.addTarget(self, action: #selector(saveButtonClecked), for: UIControlEvents.touchUpInside)
        return button
    }()
}

extension MCEditSpecificationsViewController : UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return true
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if textField == moneyView.textField {
            let b = MCString_keepTwoDecimalPlaces(textField, range, string)
            return b
        }
        return true
    }
}

extension MCEditSpecificationsViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let mediaType = info[UIImagePickerControllerMediaType] as! String
        
        if mediaType == String(kUTTypeImage) {
            let originalImage : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
            
            let rect = info[UIImagePickerControllerCropRect] as! CGRect
            
            let editedImage = originalImage.MCImageCrop(toRect: rect)
            self.isUpdateImage = true
            addImageView.image = editedImage
            picker.dismiss(animated: true, completion: nil)
        }
    }
}

